package com.example.common.security.service;
import cn.hutool.core.lang.UUID;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.constants.JwtConstants;
import com.example.common.redis.service.RedisService;
import com.example.common.core.domain.LoginUser;
import com.example.common.core.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//用户登录令牌方法
@Service
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId,String secret,Integer indentity){
        Map<String, Object> claims=new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
        String token = JwtUtils.createToken(claims, secret);
        //第三方机制中存储敏感信息 redis
        //用户身份字段 identity 1 普通用户 2 管理员用户
        //数据结构 String
        //key保证唯一 便于维护 统一前缀: logintoken:userKey

        String key= CacheConstants.LOGIN_TOKEN_KEY + userKey;
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(indentity);
        redisService.setCacheObject(key,loginUser,CacheConstants.EXP, TimeUnit.MINUTES);

        return token;
    }
}
